import { RenderComponents } from '../SDK/render.ts';
import WarmPopup from './index.vue';
import { ConfirmType, BaseReloadingType } from "./type";
import { defineAsyncComponent } from "vue";

export class Popup extends RenderComponents {

    constructor() {
        super();
    }

    /**
     * 打开对话框提示模板
     * @param options 消息模板参数
     * @param Component 组件对象
     */
    public openConfirmTemp(options: ConfirmType, Component: any): void {

        const POPUP_CONFIRM_SYMBOL = Symbol('confirm');

        const confirmCallback = options.onConfirm, cancelCallback = options.onCancel;

        options.onConfirm = (e: any) => {
            confirmCallback && confirmCallback(e);
            super.unmountComponent(component, POPUP_CONFIRM_SYMBOL);
        }

        options.onCancel = (e: any) => {
            cancelCallback && cancelCallback(e);
            super.unmountComponent(component, POPUP_CONFIRM_SYMBOL);
        }

        // 创建组件实例对象
        let component: any = super.createComponent(Component, options, null, POPUP_CONFIRM_SYMBOL);

        document.body.appendChild(component.vnode.el);
    }

    /**
     * 打开公共请求and重新请求面板
     * @param options 消息模板参数
     * @param Component 组件对象
     */
    openReloadingTemp(options: BaseReloadingType, Component: any) {

        const POPUP_RELOADING_SYMBOL = Symbol('reloading');

        const confirmCallback = options.onSuccess;

        options.onSuccess = (e) => {
            confirmCallback && confirmCallback(e);
            super.unmountComponent(component, POPUP_RELOADING_SYMBOL);
        }

        // 创建组件实例对象
        let component: any = super.createComponent(Component, options, null, POPUP_RELOADING_SYMBOL);

        document.body.appendChild((component.vnode.el) as any);

        // 返回销毁方法提供外面使用
        return () => {
            super.unmountComponent(component, POPUP_RELOADING_SYMBOL);
        }
    }
}

const POPUP = new Popup();

/**
 * 打开提示信息
 * @param options
 */
const WarmConfirm = (options: ConfirmType) => POPUP.openConfirmTemp(options, defineAsyncComponent(() => import('@/components/Warm/Popup/confirm.vue')));

/**
 * 打开公共请求and重新请求面板
 * @param options
 */
const BaseReloading = (options: BaseReloadingType) => POPUP.openReloadingTemp(options, defineAsyncComponent(() => import('./baseReloading.vue')));

export {
    WarmPopup,
    WarmConfirm,
    BaseReloading
}